//
//  QuizViewController.m
//  MatchTouch
//
//  Created by SUN DONG LEE on 13. 1. 21..
//  Copyright (c) 2013년 SUN DONG LEE. All rights reserved.
//

#import "QuizViewController.h"
#import "AppDelegate.h"
#import <sqlite3.h>

@interface QuizViewController ()

@end

@implementation QuizViewController

NSThread *t1;
int score;

NSTimer *timerLeftTime;
int leftTime;
int givenTime;
int firstGivenTime=30;
float timeGradationWidth;
int leftLife=3;

int score, finalScore, maxScore=31*3*6*100;
int highScore;

NSMutableSet *selected_nums;

NSMutableSet *tmpAnimals;

NSMutableArray *selectedArray1;
NSMutableArray *selectedArray2;

NSArray *oppTextArray1; //전체 반대말 단어 배열 1
NSArray *oppTextArray2; //전체 반대말 단어 배열 2

NSMutableArray *remainOppTexts1; //전체 반대말 단어 중 남아 있는 단어 배열 1
NSMutableArray *remainOppTexts2; //전체 반대말 단어 중 남아 있는 단어 배열 2

NSMutableArray *buttonArray; //그리드 초기화시 기존 버튼들을 모두 지우기 위해 이 어레이에 담우 둔다.

NSMutableDictionary *tagDic; //각 단어에 대한 tag를 설정해 두기 위한 딕셔너리

UIView *blockingView;

int xOffset=5;
int xWidth;

int yOffset=105;
int yHeight;

NSString *stars, *highStars;

UIImage *imageFail, *imageSuccess;

NSString *theDBPath;

- (AppDelegate *)appDelegate {
	return [[UIApplication sharedApplication] delegate];
}


-(void)scoreAni:(id)object {
    NSLog(@"score = %d",score);
    
    //if ([[NSThread currentThread] isCancelled] == YES);
    
    //_label_result_finalScore.text = [NSString stringWithFormat:@"%d",finalScore];
    int i;
    for (i=0; i<score; i=i+1000) {
      _label_result_finalScore.text = [NSString stringWithFormat:@"%d",i];
        NSLog(@"%@\n",_label_result_finalScore.text);
        sleep(1/5);
    }
    _label_result_finalScore.text = [NSString stringWithFormat:@">> %d //",score];
    NSLog(@"final score = %d",score);
}


- (void)showResult:(Boolean)isSuccess {
    [_label_left_time setAlpha:0.0];
    [_viewTimeRect setAlpha:0.0];
    [_label_left_life setAlpha:0.0];
    [_finger1 setAlpha:0.0];
    [_finger2 setAlpha:0.0];
    [_finger3 setAlpha:0.0];
    [_label_high_score setAlpha:0.0];
    [_label_score setAlpha:0.0];
    [_img_result_NewHighScore setAlpha:0.0];

    if (isSuccess) { //Stage 성공
        _label_result_title.text=@"LEVEL Cleared!";
        [_label_result_finalScore setAlpha:1.0];
        [_label_result_highScore setAlpha:1.0];
        
        if ((_received_stage_num == [self appDelegate].highWaterMark) && (_received_stage_num < [[self appDelegate].stages count])) {
            [self appDelegate].highWaterMark++;
        }
        
        //최종 점수 환산 및 표시
        finalScore=score*100*(leftLife+1)*(leftTime+1);
        //_label_result_finalScore.text = [NSString stringWithFormat:@"%d",finalScore];
        //[self scoreAni:finalScore];
        
        //최종 점수에 따라 별 표시 //TODO: 별이 애니메이션 되면서 찍히고 소리도 나도록... , 또 HighScore이면 New High Score 도장찍기 애니메이션
        if (finalScore>maxScore*0.8) {
            stars=[NSString stringWithFormat:@"***"];
        } else if (finalScore>maxScore*0.5) {
            stars=[NSString stringWithFormat:@"**"];
        } else {
            stars=[NSString stringWithFormat:@"*"];
        }
        _label_stars.text = stars;
        
        //finalScore가 highScore보다 크면 highScore갱신
        if (highScore<finalScore) {
            highScore=finalScore;
            highStars=stars;
            
            [[self appDelegate].highScores setObject:[NSNumber numberWithLong:highScore] forKey:[NSNumber numberWithInt:(int)_received_stage_num]];
            
            [[self appDelegate].highStars  setObject:highStars forKey:[NSNumber numberWithInt:(int)_received_stage_num]];
            
            sqlite3 * database;
            const char * sql = "update score set highscore = ?, highstar = ? where no = ?";
            sqlite3_stmt * update_statement = nil;
            NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString * docsDir = [paths objectAtIndex:0];
            NSString * thePath = [docsDir stringByAppendingPathComponent:@"speedmatch.db"];
            int ret = sqlite3_open([thePath UTF8String], &database);

            if(ret != SQLITE_OK) {
                NSLog(@"Problem with opening database");
                NSLog(@"Error Code : %d, message '%s'", ret, sqlite3_errmsg(database));
                return;
            } else {
                NSLog(@"OK 000");
            }
            
            NSString *sql_create_table = @"CREATE TABLE IF NOT EXISTS score (no INTEGER PRIMARY KEY, highscore INTEGER, highstar VARCHAR)";
            char *err;
            if (sqlite3_exec(database, [sql_create_table UTF8String], NULL, NULL, &err) != SQLITE_OK) {
                sqlite3_close(database);
                NSAssert(0,@"Table failed to create.");
            }
            
            int e = sqlite3_prepare_v2(database, sql, -1, &update_statement, nil);

            if(e != SQLITE_OK) {
                NSLog(@"Problem with updateEntryWithUniqueID");
                NSLog(@"Error Code: %d, message '%s'", e, sqlite3_errmsg(database));
                return;
            } else {
                NSLog(@"OK 111");
            }

            sqlite3_bind_int(update_statement, 1, highScore);
            sqlite3_bind_text(update_statement, 2, [highStars UTF8String], -1, SQLITE_TRANSIENT);
            sqlite3_bind_int(update_statement, 3, (int)_received_stage_num);

            if(sqlite3_step(update_statement) != SQLITE_DONE) {
                NSLog(@"Problems updating entry in reminder");
            } else {
                NSLog(@"OK 222");
            }
            
            /* Finished */
            sqlite3_finalize(update_statement);
            
            NSString * query  = [NSString stringWithFormat:@"update score set highscore = %d, highstar= '%@' where no = %d",highScore,highStars,(int)_received_stage_num];
            
            [[self appDelegate] executeQuery:query];

            [_label_result_highScore setAlpha:0.0];
            [_img_result_NewHighScore setAlpha:1.0];
        } else { //이전 highScore가 있으면
            if ([[self appDelegate].highStars objectForKey:[NSNumber numberWithInt:_received_stage_num]]!=NULL) {
                highStars=[[self appDelegate].highStars objectForKey:[NSNumber numberWithInt:_received_stage_num]];
                _label_result_highScore.text = [NSString stringWithFormat:@"BEST %@ %@",[[self appDelegate].highScores objectForKey:[NSNumber numberWithInt:_received_stage_num]],highStars];

                [_label_result_highScore setAlpha:1.0];
            }
        }
        
        
        [_resultImage setImage:imageSuccess];
        [_view_result setBackgroundColor:[UIColor greenColor]];

    } else { //Stage 실패
        _label_result_title.text=@"LEVEL Failed!";
        [_label_result_finalScore setAlpha:0.0];
        [_label_result_highScore setAlpha:0.0];
        
        //_label_stars.text = [NSString stringWithFormat:@"ㅠ.ㅠ"]; //TODO: 실패시 비웃는 돼지 그림 애니메이션
        _label_stars.text = [NSString stringWithFormat:@""];
        
        [_resultImage setImage:imageFail];
        [_view_result setBackgroundColor:[UIColor redColor]];
        //<##>
        [[self appDelegate] soundPlay:@"child_crying.mp3"];
    }

    [_view_result setHidden:false];
    if ((_received_stage_num<18)&&([self appDelegate].highWaterMark>_received_stage_num)) {
        [_buttonResultNext setAlpha:1.0];
    } else {
        [_buttonResultNext setAlpha:0.0];
    }
    
    blockingView=[[UIView alloc] initWithFrame:[UIScreen mainScreen].applicationFrame];
    blockingView.backgroundColor = [UIColor blackColor];
    [blockingView setAlpha:0.5];
    [self.view addSubview:blockingView];
    [self.view addSubview:_view_result];
    [timerLeftTime invalidate];
    
    //[self scoreAni:finalScore];
    score = finalScore;
    [t1 start];
    
}

- (void)setOppTextArrays {
    _label_stage_num.text = [NSString stringWithFormat:@"LEVEL %ld", (long)_received_stage_num];

    oppTextArray1 = [[NSArray alloc] initWithArray:[[[self appDelegate].stages objectAtIndex:_received_stage_num-1] objectAtIndex:0]];
    oppTextArray2 = [[NSArray alloc] initWithArray:[[[self appDelegate].stages objectAtIndex:_received_stage_num-1] objectAtIndex:1]];

    remainOppTexts1 = [[NSMutableArray alloc] initWithArray:oppTextArray1];
    remainOppTexts2 = [[NSMutableArray alloc] initWithArray:oppTextArray2];

    NSLog(@"setOppTextArrays ==>[remainOppTexts1 count]=%lu, [remainOppTexts2 count]=%lu",(unsigned long)[remainOppTexts1 count],(unsigned long)[remainOppTexts2 count]);
}

- (void)setTagForWords {
    tagDic = [[NSMutableDictionary alloc] init];
    int i=0;
    for (NSString *str in oppTextArray1) {
        [tagDic setValue:[NSNumber numberWithInt:i] forKey:str];
        i++;
    }
    i=0;
    for (NSString *str in oppTextArray2) {
        [tagDic setValue:[NSNumber numberWithInt:i] forKey:str];
        i++;
    }
}

int random_num;
NSString *animalName;
NSString *animalName2;

bool isPic=true;
int seqAnimal=0;

- (void)initializeQuiz {
    score=0;
    _label_score.text=[NSString stringWithFormat:@"Score: %d",score];
    
    NSLog(@"received_stage_num==>%ld",(long)_received_stage_num);
    
    highScore=[[[self appDelegate].highScores objectForKey:[NSNumber numberWithInt:(int)_received_stage_num]] intValue];
    if (highScore==0) {
        [_label_high_score setAlpha:0.0];
    } else {
        [_label_high_score setAlpha:1.0];
        
        NSLog(@"HighScore: %d",highScore);
        
        _label_high_score.text=[NSString stringWithFormat:@"HighScore: %d",highScore];
    }
    
    NSLog(@"makeGrid 시작");
    [self makeGrid];
    NSLog(@"makeGrid 종료");
    
    //아래는 버튼 생성 후 그 외 초기화 작업들..
    seqAnimal=0;
    
    leftTime=givenTime=firstGivenTime-(int)_received_stage_num;
    leftLife=3;

    isSecondButton=false;

    [blockingView removeFromSuperview];

    _label_left_time.textColor=[UIColor blackColor];
    //viewTimeRect.backgroundColor=[UIColor darkGrayColor];
    _viewTimeRect.backgroundColor=[UIColor blackColor];
    //viewTimeRect.backgroundColor=[UIColor greenColor];
    _label_left_life.textColor=[UIColor blackColor];
    [_finger1 setAlpha:1.0];
    [_finger2 setAlpha:1.0];
    [_finger3 setAlpha:1.0];

    _label_left_time.text=[NSString stringWithFormat:@"Time: %d",leftTime];
    _label_left_life.text=[NSString stringWithFormat:@"Life: %d",leftLife];
    
    timerLeftTime = [NSTimer scheduledTimerWithTimeInterval:1 target:self
                                                   selector:@selector(effect:)
                                                   userInfo:nil
                                                    repeats:YES];
    
    NSLog(@"initializeQuiz 종료");
    
    
    
    t1 = [[NSThread alloc] initWithTarget:self selector:@selector(scoreAni:) object:nil];
    
}

//문제 버튼을 만듦, 초기화 작업에 해당하므로 버튼 생성 후 여러 초기화 작업을 수행함.
- (void)makeGrid {
    
    for (UIButton *toRemoveButton in buttonArray) //그리드 생성전 기존 버튼들을 화면에서 모두 지움
    {
        [toRemoveButton removeFromSuperview];
    }
    
    [buttonArray removeAllObjects]; //그리드 생성전 기존 버튼들을 모두 지움
    
    NSLog(@"[remainOppTexts1 count]=%lu, [remainOppTexts2 count]=%lu",(unsigned long)[remainOppTexts1 count],(unsigned long)[remainOppTexts2 count]);
    seqAnimal=0;
    [selected_nums removeAllObjects];
    [selectedArray1 removeAllObjects];
    [selectedArray2 removeAllObjects];
    [tmpAnimals removeAllObjects];

    //남아 있는 단어 개수 범위내에서 6개 임의의 숫자를 selectedAnimals에 넣기
    for (int i=0; i<6; i++) {//6개의 유일한 동물 숫자(배열에서의 순서) 집합 만들기
        do {
            random_num = arc4random() % [remainOppTexts1 count];
        } while ([selected_nums containsObject:[NSNumber numberWithInt:random_num]]);
        [selected_nums addObject:[NSNumber numberWithInt:random_num]];
    }

    for (NSNumber *n in selected_nums) { //selected_nums는 집합(랜덤 6개 숫자)
        [selectedArray1 addObject:n]; //selected_numbs과 동일한 것을 배열에 넣은 것(랜덤 6개 숫자)
    }

    for (NSNumber *n in selected_nums) {
        do {
            random_num = arc4random() % 6;
        } while ([tmpAnimals containsObject:[NSNumber numberWithInt:random_num]]);
        [tmpAnimals addObject:[NSNumber numberWithInt:random_num]];
        
        [selectedArray2 addObject:[selectedArray1 objectAtIndex:random_num]];
    }
    
    NSLog(@"버튼 생성 시작");
    for (int y=0; y<ROWS; y++) {
        for (int x=0; x<COLUMNS; x++) {
            UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; //버튼 생성

            //예전 방식대로 rouned button 만들기
            button.layer.cornerRadius = 8;
            button.layer.borderWidth = 1;
            button.backgroundColor=[UIColor colorWithRed:1 green:1 blue:1 alpha:1];
            button.layer.borderColor = [UIColor grayColor].CGColor;
            button.clipsToBounds = YES;

            [button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside]; //버튼셀렉터 설정
            
            if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) { //iPhone
                CGSize result = [[UIScreen mainScreen] bounds].size;
                if(result.height == 480)
                {
                    // iPhone Classic
                    button.frame = CGRectMake((xWidth+xOffset)*x+xOffset, (yHeight+xOffset)*y+yOffset, xWidth, yHeight);
                }
                if(result.height == 568)
                {
                    // iPhone 5
                    button.frame = CGRectMake((xWidth+xOffset)*x+xOffset, (yHeight+xOffset)*y+yOffset, xWidth, yHeight);
                }
                
                
            } else { //iPad
                button.frame = CGRectMake(200*x+90, 200*y+170, 180.0, 180.0); //버튼 위치와 크기 설정
            }
            
            if (isPic) {
                isPic = false;
                animalName = [remainOppTexts1 objectAtIndex:[[selectedArray1 objectAtIndex:seqAnimal] intValue]];
                [button setTitle:animalName forState:UIControlStateNormal]; //버튼 타이틀 설정
                if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
                    if (animalName.length > 9) {
                        button.titleLabel.font = [UIFont boldSystemFontOfSize:13];
                    } else if (animalName.length > 11) {
                        button.titleLabel.font = [UIFont boldSystemFontOfSize:10];
                    } else { //animalName.length <= 9
                        button.titleLabel.font = [UIFont boldSystemFontOfSize:15];
                    }
                } else {
                    if (animalName.length > 9) {
                        button.titleLabel.font = [UIFont boldSystemFontOfSize:27];
                    } else if (animalName.length > 11) {
                        button.titleLabel.font = [UIFont boldSystemFontOfSize:25];
                    } else {
                        button.titleLabel.font = [UIFont boldSystemFontOfSize:30];
                    }
                }
            } else {
                isPic = true;
                animalName2 = [remainOppTexts2 objectAtIndex:[[selectedArray2 objectAtIndex:seqAnimal++] intValue]];
                [button setTitle:animalName2 forState:UIControlStateNormal]; //버튼 타이틀 설정
                if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
                    if (animalName2.length > 9) {
                        button.titleLabel.font = [UIFont boldSystemFontOfSize:13];
                    } else if (animalName2.length > 11) {
                        button.titleLabel.font = [UIFont boldSystemFontOfSize:10];
                    } else { //animalName2.length <= 9
                        button.titleLabel.font = [UIFont boldSystemFontOfSize:15];
                    }
                } else {
                    if (animalName2.length > 9) {
                        button.titleLabel.font = [UIFont boldSystemFontOfSize:27];
                    } else if (animalName2.length > 11) {
                        button.titleLabel.font = [UIFont boldSystemFontOfSize:25];
                    } else {
                        button.titleLabel.font = [UIFont boldSystemFontOfSize:30];
                    }
                }
            }
            
            [[self view] addSubview:button]; //버튼을 뷰에 추가하기
            
            [buttonArray addObject:button]; //추후 초기화시 기존 버튼들을 모두 지우기 위해 여기에 저장해 둠.
            
        }
    }
}

UIButton *preButton;
//bool isSecondButton=false;
bool isSecondButton;

int x,y;

UIImageView *tmpImageView;

- (void)buttonClicked:(UIButton*)button
{
    if (isSecondButton) {
        isSecondButton=false;
        if ([[tagDic objectForKey:preButton.titleLabel.text] intValue] == [[tagDic objectForKey:button.titleLabel.text] intValue]) {

            _label_score.text=[NSString stringWithFormat:@"Score: %d",++score*100];
            //_label_score.text=[NSString stringWithFormat:@"Score: %d",((score*100*(leftLife+1)*(leftTime+1))+1)*100];
            
            
            [[self appDelegate] soundPlay:@"O.mp3"];

            [preButton setAlpha:0];
            [button setAlpha:0];

            //remainOppTexts에서 맞춘 animal 빼기
            [remainOppTexts1 removeObject:preButton.titleLabel.text];
            [remainOppTexts2 removeObject:preButton.titleLabel.text];
            [remainOppTexts1 removeObject:button.titleLabel.text];
            [remainOppTexts2 removeObject:button.titleLabel.text];
            
            preButton = nil;
        } else {
            if (leftLife>0) {
                
                score--;
                if (score<0) {
                    score=0;
                }
                _label_score.text=[NSString stringWithFormat:@"Score: %d",score*100];
                //_label_score.text=[NSString stringWithFormat:@"Score: %d",(score*100*(leftLife+1)*(leftTime+1))*100];
            
                
                
                [[self appDelegate] soundPlay:@"X.mp3"];

                [preButton setAlpha:1.0];
                [preButton setEnabled:true];
                leftLife--;
                _label_left_life.text=[NSString stringWithFormat:@"Life: %d",leftLife];
                if (leftLife==1) {
                    _label_left_life.textColor=[UIColor redColor];
                } else if (leftLife==0) {
                    [self showResult:false];
                }
                
                switch (leftLife) {
                    case 0:
                        [_finger1 setAlpha:0.0];
                        [_finger2 setAlpha:0.0];
                        [_finger3 setAlpha:0.0];
                        break;
                    case 1:
                        [_finger1 setAlpha:1.0];
                        [_finger2 setAlpha:0.0];
                        [_finger3 setAlpha:0.0];
                        break;
                    case 2:
                        [_finger1 setAlpha:1.0];
                        [_finger2 setAlpha:1.0];
                        [_finger3 setAlpha:0.0];
                        break;
                    case 3:
                        [_finger1 setAlpha:1.0];
                        [_finger2 setAlpha:1.0];
                        [_finger3 setAlpha:1.0];
                        break;
                    default:
                        break;
                }
            }
        }
    } else {
        isSecondButton=true;
        [button setEnabled:false];
        [button setAlpha:0.2];
    }

    preButton = button;

    if ([remainOppTexts1 count]==0) {
        //[[self appDelegate] soundPlay:@"Kids Cheering.mp3"];
        [[self appDelegate] soundPlay:@"Clapping Crowd Studio 01.mp3"];
        [self showResult:true];
    }
}

- (IBAction)act_again:(id)sender {
    NSLog(@"act_again");
    
    [t1 cancel];
    
    [_label_left_time setAlpha:0.0]; //[_label_left_time setAlpha:1.0];
    [_viewTimeRect setAlpha:1.0];
    [_label_left_life setAlpha:0.0]; //[_label_left_life setAlpha:1.0];
    [_finger1 setAlpha:1.0];
    [_finger2 setAlpha:1.0];
    [_finger3 setAlpha:1.0];
    [_label_high_score setAlpha:1.0];
    [_label_score setAlpha:1.0];

    [_view_result setHidden:true];
    
    remainOppTexts1 = [[NSMutableArray alloc] initWithArray:oppTextArray1];
    remainOppTexts2 = [[NSMutableArray alloc] initWithArray:oppTextArray2];

    [self initializeQuiz];
    [[self appDelegate] soundPlay:@"start.mp3"];
}

- (IBAction)act_next:(id)sender {
    NSLog(@"act_next");
    
    [t1 cancel];
    
    [_label_left_time setAlpha:0.0]; //[_label_left_time setAlpha:1.0];
    [_viewTimeRect setAlpha:1.0];
    [_label_left_life setAlpha:0.0]; //[_label_left_life setAlpha:1.0];
    [_finger1 setAlpha:1.0];
    [_finger2 setAlpha:1.0];
    [_finger3 setAlpha:1.0];
    [_label_high_score setAlpha:1.0];
    [_label_score setAlpha:1.0];
    
    if (_received_stage_num < [[self appDelegate].stages count]) {
        _received_stage_num++;
        
        if (_received_stage_num > [self appDelegate].highWaterMark) {
            [self appDelegate].highWaterMark++;
        }

        [_segment_stage setTitle:[NSString stringWithFormat:@"%d",(int)_received_stage_num+1] forSegmentAtIndex:_received_stage_num];
        
        [_view_result setHidden:true];
        
        [self setOppTextArrays]; //set stage
        [self setTagForWords];
        
        [self initializeQuiz];
    }
    [[self appDelegate] soundPlay:@"start.mp3"];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self initializeQuiz];
    [_label_left_time setAlpha:0.0];
    [_label_left_life setAlpha:0.0];
    
    [[self appDelegate] soundPlayLoopStop];
    [[self appDelegate] soundPlay:@"start.mp3"];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [[self appDelegate] soundPlayLoop:@"FILE_2012022951_1_117_Soundofmusic.mp3"];
    [super viewWillDisappear:animated];
}


- (void)effect:(NSTimer *)aTimer{
    //Time Graph Logic
    if (leftTime==givenTime) {
        timeGradationWidth=_viewTimeRect.frame.size.width/(float)givenTime;
    }
    
    leftTime--;

    if (leftTime<0) { //퀴즈 시간 종료 이면...
        [self showResult:false];
    } else { //퀴즈 시간 종료 전 이면...
        if (leftTime<6) { //퀴즈 시간이 5초 이하로 남아 있으면...
            _label_left_time.textColor=[UIColor redColor];
            _viewTimeRect.backgroundColor=[UIColor redColor];
            
            if (leftTime==5) { //남은 시간이 5초일 때 한번만 경고음이 나도록
                [[self appDelegate] soundPlayAlarm:@"FILE_2012040337_1_098_알림20.mp3"];
            }
        }
        _label_left_time.text=[NSString stringWithFormat:@"Time: %d", leftTime];
        _viewTimeRect.frame = CGRectMake(_viewTimeRect.frame.origin.x,_viewTimeRect.frame.origin.y, _viewTimeRect.frame.size.width-timeGradationWidth,_viewTimeRect.frame.size.height);
    }
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // 상태바 숨기기
    if ([self respondsToSelector:@selector(setNeedsStatusBarAppearanceUpdate)]) {
        // iOS 7
        [self performSelector:@selector(setNeedsStatusBarAppearanceUpdate)];
    } else {
        // iOS 6
        [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationSlide];
    }
    
    CGSize result = [[UIScreen mainScreen] bounds].size;

    xWidth=(result.width-(xOffset*4))/COLUMNS;
    yHeight=(result.height-(yOffset*2))/ROWS;
    
    
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) { //iPhone
        
        if(result.height == 480)
        {
            // iPhone Classic
        }
        if(result.height == 568)
        {
            // iPhone 5
        }
    } else { //iPad
        
    }

    selected_nums = [[NSMutableSet alloc] init];
    
    tmpAnimals = [[NSMutableSet alloc] init];
    selectedArray1 = [[NSMutableArray alloc] init];
    selectedArray2 = [[NSMutableArray alloc] init];
    
    buttonArray = [[NSMutableArray alloc] init];
    
    [self setOppTextArrays];
    [self setTagForWords];
    
    //[[self appDelegate] soundPlay:@"start.mp3"];
    [_view_result setHidden:true];
    
    imageFail = [UIImage imageNamed:@"ICO_FACE_CRYING_BIG.png"];
    imageSuccess = [UIImage imageNamed:@"ICO_FACE_LOVING_BIG.png"];
}

// 상태바 숨기기
- (BOOL)prefersStatusBarHidden {
    return YES;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (IBAction)act_back_button:(id)sender {
    [timerLeftTime invalidate];
    [self performSegueWithIdentifier:@"segue_quiz_2_stages" sender:self];
}

@end
